package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Travel;
import cn.wolfcode.trip.base.domain.TravelContent;
import cn.wolfcode.trip.base.mapper.TravelContentMapper;
import cn.wolfcode.trip.base.mapper.TravelMapper;
import cn.wolfcode.trip.base.query.TravelQuery;
import cn.wolfcode.trip.base.service.ITravelService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.applet.Main;

import java.util.Date;
import java.util.List;

/**
 * Created by 13925 on 2018/11/1.
 */

/**
 * 游记服务层实现类
 */
@Service
public class TravelServiceImpl implements ITravelService {
    @Autowired
    private TravelMapper travelMapper;


    @Autowired
    private TravelContentMapper travelContentMapper;

    @Override
    public PageInfo query(TravelQuery qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<Travel> list = travelMapper.selectForList(qo);
        return new PageInfo(list);
    }

    @Override
    public void save(Travel travel) {
        //设置游记创建时间
        travel.setCreateTime(new Date());
        //设置最新更新时间
        travel.setLastUpdateTime(new Date());
        //游记的保存
        travelMapper.insert(travel);
        //游记的文本内容保存
        TravelContent travelContent = travel.getTravelContent();
        travelContent.setId(travel.getId());

        travelContentMapper.insert(travelContent);

    }

    @Override
    public Travel get(Long id) {
        return travelMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(Travel travel) {
        //更新最后更新时间
        travel.setLastUpdateTime(new Date());
        //更新游记
        travelMapper.updateByPrimaryKey(travel);
        TravelContent travelContent = travel.getTravelContent();
        //更新游记内容
        travelContent.setId(travel.getId());
        travelContentMapper.updateByPrimaryKey(travelContent);
    }

    public void changeState(Travel travel) {
        //当状态是发布状态的时候 添加最后修改游记时间
        if (travel.getState() == Travel.STATE_RELEASE) {
            travel.setLastUpdateTime(new Date());
        }
        travelMapper.updateTravelState(travel);
    }

    public TravelContent getTravelContent(Long id) {
        return travelContentMapper.selectByPrimaryKey(id);
    }
}
